import { Injectable } from '@nestjs/common';
import { CreateVerifyCodeDto } from './dto/create-verify-code.dto';
import { UpdateVerifyCodeDto } from './dto/update-verify-code.dto';
import utils from 'src/utils';

import * as svgCaptcha from 'svg-captcha';

@Injectable()
export class VerifyCodeService {
  create(createVerifyCodeDto: CreateVerifyCodeDto) {
    return 'This action adds a new verifyCode';
  }
  // 生成验证码响应给前端
  createStrCode(req: any, res: any) {
    let fontCount = utils.Number.getRadomInt(3, 6);
    const captcha = svgCaptcha.create({
      size: fontCount,//生成几个验证码
      fontSize: utils.Number.getRadomInt(30, 50), //文字大小
      width: 100,  //宽度
      height: 30,  //高度
      background: utils.Color.getRandom16Color(),  //背景颜色
    });
    req.session.code = captcha.text //存储验证码记录到session
    res.type('image/svg+xml');
    res.send(captcha.data);
  };
  // 验证验证码
  submitStrCode(req: any, res: any) {
    let code = req.session.code;
    // console.log('submitStrCode:', req.session.code, req.body);
    let verifyRes = code === req.body.code;
    if (verifyRes) {
      return sendData(200, 'verify success', { message: '验证成功' });
    } else {
      return sendData(203, 'verify fail', { message: '验证失败' });
    }
  };
}


function sendData(code: number, msg: any, data: Record<string, any> = {}) {
  return {
    code,
    msg,
    data
  }
}
